package admin.controllers;

import helpers.CookieHelper;
import helpers.EmailHelper;
import helpers.UrlHelper;
import helpers.ValidateHelper;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import search.ArticleSearchEngine;
import systems.ConfigSystem;
import systems.Recently;

import entities.Article;
import entities.SiteConfig;
import entities.User;

import admin.models.ArticleModel;
import admin.models.UserModel;

public class ArticleDeleteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setContentType("text/html");
		
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		String urlRedirect = (String) request.getParameter("redirect");
		String sendmail = (String) request.getParameter("sendmail");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/article/list");
			return ;
		}
		
		try {
			ArticleModel articleModel = ArticleModel.getInstance();
			Article article = articleModel.getArticle(id);
			articleModel.delete(article);
			
			//Remove recently cache
			Recently.remove(article);
			
			/***** SEND MAIL *****/
			if (siteConfig.getSubmitStatus() == 2 && sendmail != null) {
				String fromEmail = siteConfig.getContactEmail();
				String toEmail = article.getEmail();
				
				String serverUrl = UrlHelper.getServerUrl(request);
				String serverName = UrlHelper.getDomainServer(request);
				String strUrl = serverUrl + "/email-delete-article?id="+article.getId()+"&key=" + article.getAuthKey();
				String strSubject = "Delete Article with id " + article.getId();
				
				if (toEmail.isEmpty() && !article.getCreator().isEmpty()) {
					UserModel userModel = UserModel.getInstance();
					User author = userModel.getUser(article.getCreator());
					if (author != null) {
						toEmail = author.getUsername();
					}
				}
				
				if(!toEmail.isEmpty() && ValidateHelper.isEmail(toEmail)) {
					System.out.println(strUrl + " from " + fromEmail + " -> to " + toEmail);
					EmailHelper.sendMailFromUrl(serverName + " <" + fromEmail + ">", strSubject, strUrl, toEmail);
				}
			} 
			/***** END SEND MAIL *****/
			
			
			request.setAttribute("success", "Delete success article " + id);
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
		if (urlRedirect == null || urlRedirect.isEmpty()) {
			response.sendRedirect("/admin/article/list");
			return;
		} else {
			response.sendRedirect(urlRedirect);
			return;
		}
	}
}
